﻿/*
* 创建者：LIYINFAI
* 创建时间：2023/10/24 9:35:26
* 描述：
* --------------------------------------
* 修改说明：
* --------------------------------------
*/
using CommonLibrary;
using CommonLibrary.Forms;
using System;
using System.Diagnostics;
using System.Drawing;

namespace BusinessLibrary
{
    /// <summary>
    /// 心跳类
    /// </summary>
    public class Heartbeat : IPlugin
    {
        /// <summary>
        /// 描述信息
        /// </summary>
        public string Description => "往PLC里写入上位机心跳";
        /// <summary>
        /// 执行方法
        /// </summary>
        /// <param name="pluginParam">参数</param>
        /// <returns></returns>
        public string Excute(PluginParamEntity pluginParam)
        {
            string result = string.Empty;
            if (pluginParam != null
                && APPInstance.PLC != null
                && APPInstance.PLC.IsConnected
                && pluginParam.Identity.ToUpper().Equals("HEARTBEAT_PLC"))
            {
                result = HeartbeatPLC(pluginParam);
            }
            return result;
        }
        /// <summary>
        /// 返回一个窗口
        /// </summary>
        /// <param name="pluginParam"></param>
        /// <returns></returns>

        public HWFrmWithTitle GetForm(PluginParamEntity pluginParam)
        {
            return null;
        }
        /// <summary>
        /// 返回一个 Bitmap
        /// </summary>
        /// <returns></returns>
        public Bitmap GetBitmap()
        {
            return null;
        }
        /// <summary>
        /// HEARTBEAT_PLC
        /// 往PLC写入上位机心跳
        /// </summary>
        /// <returns></returns>
        private string HeartbeatPLC(PluginParamEntity pluginParam)
        {
            string methodName = "上位机心跳";
            this.Info($"【{pluginParam.Tag}】开始 - {methodName}");
            try
            {
                if (pluginParam != null && APPInstance.PLC != null && APPInstance.PLC.IsConnected)
                {
                    short heartbeat = GlobalStatus.APP == EAppStatus.RUN ? (short)1 : (short)0;
                    string address = AppPLCSetting.Instance().PCHeartbeat;
                    APPInstance.PLC.Write(address, heartbeat);
#if DEBUG
                    Debug.WriteLine($"HEART - {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}");
#endif
                }
            }
            catch (Exception ex)
            {
                this.Error(ex);
            }
            this.Info($"【{pluginParam.Tag}】结束 - {methodName}");
            return string.Empty;
        }
    }
}
